<?php
namespace app\index\controller;
use caretree\Caretree; 
class Category extends Base
{
	//select g.id,g.goods_name,sum(og.goods_num) xl
	// from tp_goods g
	// left join tp_order_goods og
	// on(g.id = og.goods_id and og.order_id in (select id from tp_order where pay_status = 1))
	// group by g.id
    public function index($id)
    {
		$cateInfo = db('category')->where('id',$id)->find($id);  //通过id找到该对象
		// cache('attrRes_'.$id,null);  删除筛选属性缓存逻辑
		if(!cache('attrRes_'.$id)){
		// $cateInfo = db('category')->where('id',$id)->value('search_attr_ids'); //属性id
		$sai = $cateInfo['search_attr_ids'];
		$attrRes = db('attr')->field('id,attr_name')->where(array('id'=>array('in',$sai)))->select(); //通过属性ID查询attr
		// dump($attrRes);die;
		$attrValues = []; //声明一个空数组
		foreach($attrRes as $k => $v){
			$attrValues = db('goods_attr')->field('attr_id,attr_value,goods_id')->where(array('attr_id'=>$v['id']))->select();//查询goods_attr 通过attr_id
			
			//判断当前商品是否属于当前栏目
			foreach($attrValues as $k1 => $v1){ 
				$categoryId = db('goods')->where('id',$v1['goods_id'])->value('category_id'); //通过id查询category_id
				if($categoryId != $id){
					unset($attrValues[$k1]);
				}
			}
			
		if(!$attrValues){
			unset($attrRes[$k]);
		}else{ //
			$attrRes[$k]['attr_values']=assoc_unique($attrValues,'attr_value');
		}
		
	}
		cache('attrRes_'.$id,$attrRes,3600);
		}else{
			$attrRes = cache('attrRes_'.$id);
		}

		//获取品牌信息
		$_brandRes = db('goods')->field('brand_id')->where(array('category_id'=>$id))->select();
		$_brandRes = assoc_unique($_brandRes,'brand_id');
		// dump($_brandRes);die;
		$brandRes = array();
		foreach($_brandRes as $k => $v){
			if($v['brand_id']){
				$brandRes[] = db('brand')->field('id,brand_name')->find($v['brand_id']);
			}
		}
		// dump($_brandRes);die;
	//	 cache('priceSection_'.$id,null);  删除计算区间价格缓存
	if(!cache('priceSection_'.$id)){
		//计算价格区间的逻辑
	$goodsPrice = db('goods')->field('MIN(shop_price) min_price,MAX(shop_price) max_price')->where(array('category_id'=>$id))->find();
	// dump($goodsPrice);die;
	//计算价格区间的平均差值
	$sprice = ceil(($goodsPrice['max_price']-$goodsPrice['min_price'])/$cateInfo['ps_num']);
	$priceSection = [];
	$firstPrice =intval($goodsPrice['min_price']);
	for($i = 0; $i < $cateInfo['ps_num']; $i++){
		if($i==0){
			$_priceSection = $firstPrice.'-'.(ceil(($firstPrice+$sprice)/10)*10-1);
		}elseif($i == ($cateInfo['ps_num']-1)){
			$_priceSection = (ceil($firstPrice/10)*10).'-'.intval($goodsPrice['max_price']);
		}else{
			$startPrice = ceil($firstPrice/10)*10;
			$endPrice = ceil(($firstPrice+$sprice)/10)*10-1;
			$_priceSection = $startPrice.'-'.$endPrice;
		}
		$_priceSection =explode('-',$_priceSection);
		$startPrice = $_priceSection[0];
		$endPrice =  $_priceSection[1];
		$goodsCount = db('goods')->where(array(
			'shop_price'=>array('between',array($startPrice,$endPrice)),
			'category_id'=>array('eq',$id),
			'on_sale'=>array('eq',1))
		)->count();
		if($goodsCount){
			$priceSection[] = $startPrice.'-'.$endPrice;
		}
		$firstPrice += $sprice;
	}	
	// dump($priceSection);die;
	cache('priceSection_'.$id,$priceSection,3600);
	}else{
		$priceSection = cache('priceSection_'.$id);
	}
	$ob = input('ob') ? input('ob') : 'xl';
	$ow = input('ow') ? input('ow') : 'desc';
	$goodsRes = $this->search_goods($id);
	// dump($goodsRes->all());
	//筛选属性的高亮状态的处理
	$filterAttr = input('filter_attr');
	$attrValue = array();
	$attrId = array();
	if($filterAttr){
		$filterAttr = explode('.',$filterAttr);
		//白色-1,500G-3
		foreach($filterAttr as $k => $v){
			if($v){
				$attr = explode('-',$v);
				$attrValue[] = $attr[0];
				$attrId[] = $attr[1];
			}
		}
	}
	$price = input('price');
	$this->assign([
			'attrRes'=>$attrRes,
			'priceSection' => $priceSection,
			'brandRes'=>$brandRes,
			'goodsRes'=>$goodsRes,
			'cateId' => $id,
			'price' => $price,
			'ob' => $ob,
			'ow' => $ow,
			'attrValue'=> $attrValue,
            'attrId'   => $attrId
		]);	
		return view('Category');
   }
   
   public function getCateInfo($id){
	   $mCategory = model('Category');
	   $cateRes =$mCategory->getSonCates($id);
	   $cwRes = $mCategory->getCategoryWords($id);
       $brands = $mCategory->getCategoryBrands($id);
	   // dump($brands);die;
	   $data=array();
	 
	   $cat='';
	   foreach($cateRes as $k => $v){
		   $cat.='<dl class="dl_fore1"><dt><a href="'.url('index/Category/index',['id'=>$v['id']]).'" target="_blank">'.$v['cate_name'].'</a></dt><dd>';
			foreach($v['children'] as $k1 =>$v1){
				 $cat.='<a href="'.url('index/Category/index',['id'=>$v1['id']]).'" target="_blank">'.$v1['cate_name'].'</a>';
			}
		   $cat.='</dd></dl><div class="item-brands"><ul></ul></div><div class="item-promotions"></div>';
		 }
		 
		 $channels='';
		 foreach($cwRes as $k => $v){
			 $channels .= '<a href="'.$v['link_url'].'" target="_blank">'.$v['word'].'</a>';
		 }
		 $brandsAdContent='';
	   $brandsAdContent.='
	   <div class="cate-brand">';
			foreach($brands['brands'] as $k=>$v){
				$brandsAdContent.=
				'<div class="img">
					<a href="'.$v['brand_url'].'" target="_blank" title="'.$v['brand_name'].'"><img src="'.config('view_replace_str.__uploads__').'/'.$v['brand_img'].'"></a>
				</div>';
			}
	   $brandsAdContent.='</div>';
	   $brandsAdContent.='
	   <div class="cate-promotion">
	       <a href="'.$brands['promotion']['pro_url'].'" target="_blank"><img width="199" height="97" src="'.config('view_replace_str.__uploads__').'/'.$brands['promotion']['pro_img'].'"></a>
	   </div>';
	   $data['topic_content']=$channels;
	   $data['cat_content']= $cat;
	   $data['brands_ad_content']=$brandsAdContent;
	   $data['cat_id']=$id;
	   return json($data);
   }
   public function search_goods($cateId){
		$cateTree = new Caretree();
		$ids = $cateTree->childrenids($cateId,db('category'));
		$ids[] = $cateId;   
	//搜索条件
	   $where = array(
		   'g.on_sale' => 1,
		    // 'g.category_id'=> ['in',$ids]
	   );
	   //价格筛选
	   if(input('price')){
		$priceArr = explode('-',input('price'));
		$where['g.shop_price']=array('between',array($priceArr[0],$priceArr[1]));
	   }
	   //品牌筛选
	   if(input('brand')){
		$where['g.brand_id']=input('brand');
	   }
	   //自定义属性筛选   filter_attr/黄色-1.100G-2.2核-3
	   $filterAttr = input('filter_attr');
	   $_attrGoodsIds=null;  // array('1,2,3,3,4','2,1,34,5')
	   if($filterAttr){
		$filterAttr = explode('.',$filterAttr);
		
		foreach($filterAttr as $k =>$v){
			if($v){  //当0作为数组下标的元素的时候,判断条件不成立为false
				$_v = explode('-',$v);
				//1,2,3,4
				$attrGoodsIds = db('goodsAttr')->field('GROUP_CONCAT(goods_id) goods_id')->where(array('attr_id' => $_v[1],'attr_value'=>$_v[0]))->find();
				// dump($attrGoodsIds['goods_id']);
				if($_attrGoodsIds == null){
					$_attrGoodsIds = explode(',',$attrGoodsIds['goods_id']); //将通过分割第一个得到的属性id查询的  goods_id  字段 
					// dump($_attrGoodsIds);
				}else{
					$tempArr = explode(',',$attrGoodsIds['goods_id']);  //array_intersect() 函数用于比较两个（或更多个）数组的键值，并返回交集。
					//  dump($tempArr);
					$_attrGoodsIds = array_intersect($_attrGoodsIds,$tempArr);   //同一个商品可以有多个属性  
					if(empty($_attrGoodsIds)){
						// dump('111');
						break;
					}
				}
				 
				if($_attrGoodsIds){
					$where['g.id'] = array('in',$_attrGoodsIds);
					
				}else{
					$where['g.id'] = array('eq',0);
				}
			}
			
		}
		
		
	}

	   //排序方式
	   $orderBy = 'xl';
	   $orderWay = 'DESC';
	   $ob = input('ob');
	   $ow = input('ow');
	   if($ob && in_array($ob,['xl','price','time','pl'])){
			$orderBy = $ob;
			if($ow && in_array($ow,['asc','desc'])){
				$orderWay = $ow;
			}
	   }
	   //查询获取数据
	   
	//    $order = array();
	   //select g.id,g.goods_name,ifnull(sum(og.goods_num),0) xl,(select count(id) from tp_comment c where g.id = c.goods_id) pl
		// from tp_goods g
		// left join tp_order_goods og
		// on(g.id = og.goods_id and og.order_id in (select id from tp_order where pay_status = 1))
		// group by g.id
		// order by xl DESC
		$goodsRes = db('goods')->field("g.id,g.goods_name,g.shop_price price,g.time,g.mid_thumb,
		ifnull(sum(og.goods_num),0) xl,(select count(id) from tp_comment c where g.id = c.goods_id) pl,(SELECT group_concat(mid_photo) from 
		tp_goods_photo gp where g.id = gp.goods_id) mid_photo,(select group_concat(id) from tp_recpos  where rec_type = 1 and id in(select recpos_id from tp_rec_item where value_type =1 and g.id = value_id)) recpos")
		->alias('g')
		->join('order_goods og','g.id = og.goods_id and og.order_id in (select id from tp_order where pay_status = 1)','LEFT')
		->where($where)->group('g.id')->order("$orderBy $orderWay")->paginate(24);
		return $goodsRes;
   }
}
